package org.jsola.hr.service.impl;

import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.util.StringUtils;
import org.jsola.admin.entity.SiteDO;
import org.jsola.core.Page;
import org.jsola.hr.provider.IAdminProviderService;
import org.jsola.hr.provider.IUserProviderService;
import org.jsola.hr.service.IHrLoginLogService;
import org.jsola.user.entity.LoginLogDO;
import org.jsola.user.query.LoginLogQuery;
import org.jsola.user.vo.LoginLogListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 登录记录
 *
 * @author zhenghua
 */
@Service("hrLoginLogServiceImpl")
public class HrLoginLogServiceImpl implements IHrLoginLogService {

    @Autowired
    private IUserProviderService userProviderService;

    @Autowired
    private IAdminProviderService adminProviderService;

    @Override
    public Page<LoginLogListVO> pageNotSiteId(LoginLogQuery loginLogQuery) {

        Map<String, SiteDO> stringSiteMap = adminProviderService.selectSiteMap();
        if (StringUtils.hasLength(loginLogQuery.getSiteName())) {
            List<String> siteIds = stringSiteMap.values().parallelStream().map(siteDO -> {
                if (siteDO.getName() != null && siteDO.getName().contains(loginLogQuery.getSiteName())) {
                    return siteDO.getId();
                }
                return null;
            }).filter(Objects::nonNull).collect(Collectors.toList());
            loginLogQuery.setSiteIds(siteIds);
        }
        Page<LoginLogDO> page = userProviderService.loginLogPageNotSiteId(loginLogQuery);
        if (CollectionUtils.isEmpty(page.getEntities())) {
            return new Page<>(loginLogQuery.getPageSize(), loginLogQuery.getPageNo());
        }
        // 查询结果 加入站点名称
        List<LoginLogListVO> serviceLogListVOList = page.getEntities().parallelStream().map(serviceLogDO -> {
            LoginLogListVO loginLogListVO = serviceLogDO.to(LoginLogListVO.class);
            SiteDO siteDO = stringSiteMap.get(serviceLogDO.getSiteId());
            if (siteDO != null) {
                loginLogListVO.setSiteName(siteDO.getName());
            }
            return loginLogListVO;
        }).collect(Collectors.toList());
        return new Page<>(serviceLogListVOList, page.getPageNo(), page.getPageSize(), page.getEntityCount());
    }
}




